// src/api/ybApi.js
import axios from 'axios'
import dayjs from "dayjs";
import {ybRequestTemplate} from "@/untils/ybRequestTemplate";

/**
 * 医保API请求专用模块
 */
const getRandom4Digits = () => {
	return Math.floor(1000 + Math.random() * 9000).toString();
}

// 创建医保接口专用axios实例
const ybApi = axios.create({
	baseURL: process.env.VUE_APP_BASE_YBHOST,
	timeout: 15000, // 医保接口响应可能较慢，设置较长超时
})

/**
 * 发送医保API请求
 * @param {Object} requestBody - 请求体数据
 * @param {Object} customHeaders - 自定义请求头
 * @returns {Promise} 包含响应数据的Promise
 */
export const sendYbRequest = async (requestBody, customHeaders = {}) => {
	try {
		// 合并默认请求头和自定义请求头
		const headers = {
			'Content-Type': 'application/json', // 默认JSON格式
			'Accept': 'application/json',
			...customHeaders // 覆盖或添加自定义头
		}

		// 发送请求
		const response = await ybApi.post('/eapdomain/callService', requestBody, {
			headers
		})

		return response.data
	} catch (error) {
		// 增强错误处理
		const errorInfo = {
			message: '医保接口请求失败',
			code: error.response?.status || 'NETWORK_ERROR',
			data: error.response?.data,
			originalError: error
		}
		console.error('医保接口错误:', errorInfo)
		throw errorInfo // 抛出结构化错误
	}
}

export const buildYbRequest = (signNo, infno) => {
	// 内部直接获取用户信息
	const userInfo = getUserInfo()
	const clinicCode = userInfo.clinicCode || ''
	const template = JSON.parse(JSON.stringify(ybRequestTemplate))
	template.body = {
		...template.body,
		infno:infno,
		msgid: `${clinicCode}${dayjs().format('YYYYMMDDHHmmss')}${getRandom4Digits()}`,
		mdtrtarea_admvs: userInfo.mdtrtareaAdmvs || '',
		recer_sys_code: '007',
		opter_type: '1',
		opter: clinicCode,
		opter_name: userInfo.staffName || '',
		inf_time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
		fixmedins_code: clinicCode,
		fixmedins_name: userInfo.clinicName || '',
		sign_no: signNo
	}

	return template
}

/**
 * 生成医保标准请求头
 * @param {Object} params - 生成参数
 * @param {string} params.infosyscode - 系统代码
 * @param {string} params.signature - 签名
 * @param {string} params.clinicCode - 医疗机构代码
 * @param {string} params.hsfNonce - 随机数
 * @param {string} params.hsfTimestamp - 时间戳
 * @returns {Object} 标准医保请求头
 */
export const generateYbHeaders = ({
									  infosyscode,
									  signature,
									  clinicCode,
									  hsfNonce,
									  hsfTimestamp
								  }) => ({
	infosyscode,
	hsf_signature: signature,
	fixmedins_code: clinicCode,
	hsf_nonce: hsfNonce,
	hsf_timestamp: hsfTimestamp
})

export const getUserInfo = () => {
	try {
		const stored = localStorage.getItem('userInfo')
		return stored ? JSON.parse(stored) : getDefaultUserInfo()
	} catch (error) {
		console.error('读取用户信息失败:', error)
		return getDefaultUserInfo()
	}
}
const getDefaultUserInfo = () => ({
	clinicCode: '',
	staffName: '',
	clinicName: '',
	mdtrtareaAdmvs: ''
})

// 使用示例：
// import { sendYbRequest, generateYbHeaders } from '@/api/ybApi'
//
// const headers = generateYbHeaders({
//   infosyscode: '12345',
//   signature: 'xxxxxx',
//   clinicCode: 'CLINIC001',
//   hsfNonce: 'nonce123',
//   hsfTimestamp: Date.now().toString()
// })
//
// const body = { key: 'value' }
//
// try {
//   const result = await sendYbRequest(body, headers)
//   console.log('接口返回:', result)
// } catch (error) {
//   console.error('请求失败:', error)
// }